package com.example.android_raspberry;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class ClientThread implements Runnable{

    public Socket socket ;
    //定义向UI线程发送消息的Handler对象
    public Handler handler;
    //定义接收UI线程的消息的Handler对象
    public Handler revhandler = new Handler();

    BufferedReader bufferedReader= null;
    OutputStream outputStream = null;
    private String ip = null;
    private int port = 0;

    public ClientThread(Handler handler, String ip, int port) {
        this.handler = handler;
        this.ip = ip;
        this.port = port;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public void run() {

        try {
            //创建套接字，获取输入流和输出流
            socket = new Socket(ip, port);
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            outputStream = socket.getOutputStream();
            //读取输入流的内容
            new Thread() {
                @Override
                public void run() {
//                    String content = null;
//                    StringBuilder stringBuffer = new StringBuilder();
//                    try
//                    {
//                        while ((content = bufferedReader.readLine()) != null){
//                            //每当读到来自服务器的数据之后，发送消息通知程序界面显示该数据
//                            stringBuffer.append(content);
//                            Message msg = handler.obtainMessage();
//                            msg.obj = stringBuffer.toString();
//                            handler.sendMessage(msg);
//
//                    }
//                    }catch (IOException e)
//                    {
//                        e.printStackTrace();
//                    }
                    try {
                        char[] buf = new char[2048];
                        int i;
                        //read.(char buf, off, int len):将从偏移量off开始的len个字节读入buf数组中，并以整数的形式返回字节数
                        while((i= bufferedReader.read(buf,0,100))!=-1) {
                            String line = new String(buf, 0, i);
                            Message msg = handler.obtainMessage();
                            msg.obj = line;
                            handler.sendMessage(msg);
                        }
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }.start();
            //为当前线程初始化Looper
            Looper.prepare();
            //创建revHandler对象
            revhandler = new Handler()
            {
                @Override
                public void handleMessage(Message msg) {
                    //接收到UI线程中用户输入的数据
                    //将用户在文本框内输入的内容写入网络
                    try {
                        System.out.println("Hello" + msg.obj.toString());
                        outputStream.write((msg.obj.toString().getBytes("utf-8")));
                        Log.d("received", msg.obj.toString());
                        outputStream.flush();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            };

            Looper.loop();
        }
        catch (SocketTimeoutException e1)
        {
            System.out.println("网络超时");
        }
        catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (socket !=null){
                try {
                    outputStream.close();
                    bufferedReader.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
